package com.admin.action;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.math.RandomUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.admin.bean.DownloadLogBean;
import com.admin.bean.MobileUserBean;
import com.admin.hessian.ScriptBean;
import com.admin.hessian.ScriptService;
import com.admin.service.BillingService;
import com.admin.service.DownloadLogService;
import com.admin.service.MobileUserService;
import com.admin.util.BaseUtil;

@Controller
@RequestMapping("/download")
public class DownLoadAction {

	private static final Logger log = Logger.getLogger(DownLoadAction.class);

	@Autowired
	private ScriptService scriptService;

	@Autowired
	private MobileUserService mobileUserService;

	@Autowired
	private BillingService billingService;
	
	@Autowired
	private DownloadLogService downloadLogService;

	//private static final int FEEID = 40;

	@RequestMapping(value = "/feeFile")
	public String feeFile(HttpServletRequest request, HttpServletResponse response) {
		String mid = request.getParameter("mid");
		if (mid == null || mid.equals("") || mid.split("#").length != 2) {
			log.error("mid为空!");
			return null;
		}
		String smsp = mid.split("#")[0];
		String ismi = mid.split("#")[1];
		MobileUserBean user = mobileUserService.findBySmspAndIsmi(smsp, ismi);
		if (user != null) {
			int SID = BaseUtil.stringToInt(request.getHeader("SID"));
			int CID = BaseUtil.stringToInt(request.getHeader("CID"));
			if (SID == 0 || CID == 0) {
				log.error("SID、CID为空!");
				return null;
			}
			int feeId = billingService.getFeeIdByCID(CID);
			
			//log.info("***************************ji lu ri zhi1111************************");
			int random = RandomUtils.nextInt(1000);
			if(random%5==0) {
				DownloadLogBean logBean = new DownloadLogBean();
				logBean.setCid(CID);
				logBean.setSid(SID);
				logBean.setImsi(ismi);
				logBean.setProvince(user.getProvinceId());
				downloadLogService.insertDwonloadLog(logBean);
			}
			
			
			StringBuffer str = new StringBuffer("<fee>");
			ScriptBean scriptBean = scriptService.getScript(feeId, mid, -1);
			if (scriptBean == null) {
				str.append("<info></info>");
			} else {
				str.append(scriptBean.getScriptStr());
			}
			str.append("</fee>");
			response.reset();
			// 设置response的Header
			response.setCharacterEncoding("UTF-8");
			response.addHeader("Content-Disposition", "attachment;filename=fee.txt");
			try {
				response.addHeader("Content-Length", "" + str.toString().getBytes("UTF-8").length);
				InputStream fis = new BufferedInputStream(new ByteArrayInputStream(str.toString().getBytes("UTF-8")));
				OutputStream toClient;
				toClient = new BufferedOutputStream(response.getOutputStream());
				response.setContentType("application/octet-stream");
				byte[] buffer = new byte[2048];
				while (fis.read(buffer) != -1) {
					toClient.write(buffer);
				}
				fis.close();
				toClient.flush();
				toClient.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
			return null;
		} else {
			return "redirect:/admin/user/reg";
		}
	}
}
